package netty.codec;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Created by IntelliJ
 * Author:熊磊
 */
public class Server {
    public static void main(String[] args) throws InterruptedException {
        //创建BossGroup 和 WorkerGroup
        // 老板组 只处理连接请求
        // worker 负责工作
        // bossgrooup 和 workerGroup 含有的子线程 NIOEventLoop 个数 默认是cpu核数 * 2
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);  //指定一个线程
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // 创建 服务器端的启动的对象 , 配置参数
            ServerBootstrap bootstrap = new ServerBootstrap();

            //设置
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128) //设置线程队列得到连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true)  //设置保持活动连接状态
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        // 给 pipline 设置处理器
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new ServerHandler());
                        }
                    });  //给workerGroup 的 EventLoop 设置处理区

            System.out.println("服务器 is ready ....");

            // 绑定一个端口 并且同步处理 , 启动
            ChannelFuture cf = bootstrap.bind(6668).sync();

            //给cf 注册监听器

            cf.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (cf.isSuccess()){
                        System.out.println("监听端口 6668成功");
                    } else {
                        System.out.println("监听端口 6668失败");
                    }
                }
            });

            //对关闭通道进行监听
            cf.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
